import time
from datetime import datetime, timedelta
import akshare as ak
import pandas as pd
from pyecharts.charts import Line
from pyecharts.globals import ThemeType
import pyecharts.options as opts
# ETF基金历史行情 - 东财

# 恒生科技指数对应基金列表
idxName = '中概互联网'
codeList = ['513050', '164906', '159605', '159607']
# codeList = ['513180']
start_date = "20150101"
df = pd.DataFrame()
min_val = 0
for i, v in enumerate(codeList):
    df_tmp = ak.fund_etf_hist_em(symbol=v, start_date=start_date, adjust="qfq")
    tmp = df_tmp.describe()
    max = tmp['最高']['max']
    min = tmp['最低']['min']
    min_val = round(min * 0.9, 3)
    withdrawal_percent = 100 - round(min * 100 / max)     # 最大回撤
    cur = df_tmp.iloc[-1]["收盘"]
    cur_percent = 100 - round(cur * 100 / max)
    print(f'{v}-最高:{max}-最低:{min}-最大回撤：{withdrawal_percent}%-当前:{cur}-当前回撤：{cur_percent}%')
    df_tmp = df_tmp.loc[:, ["日期", "收盘"]]
    df_tmp = df_tmp.rename(columns={"收盘": v})
    if i == 0:
        df = df_tmp
    else:
        df = pd.merge(df, df_tmp, on="日期", how='left').fillna(0)


# 绘制图表 - 折线图
chart = Line(
    # 设置主题、画布宽度、高度等信息
    init_opts=opts.InitOpts(theme=ThemeType.DARK, width="1400px", height="600px"),
)

# 全局设置
chart.set_global_opts(
    title_opts=opts.TitleOpts(title=f'{idxName}-基金列表'),
    # 工具箱配置
    toolbox_opts=opts.ToolboxOpts(is_show=True),
    # 区域缩放配置
    datazoom_opts=[opts.DataZoomOpts(is_show=True, range_start=0, range_end=100)],
    # y轴配置
    yaxis_opts=opts.AxisOpts(
        min_=min_val,  # 设置y轴刻度间隔为20
    )
)

chart.add_xaxis(xaxis_data=df["日期"].tolist())  # 添加x轴数据
for code in codeList:
    chart.add_yaxis(
        series_name=code,
        y_axis=df[code].tolist(),  # y轴数据
        is_connect_nones=True,  # 连接空数据
        markpoint_opts=opts.MarkPointOpts(
            data=[opts.MarkPointItem(type_="max"), opts.MarkPointItem(type_="min")],
        ),
    )
date = time.strftime('%Y%m%d', time.localtime(time.time()))
chart.render(f"ETF基金历史行情-{idxName}-{date}.html")